package com.xyz.livelib.camera;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import javax.microedition.khronos.egl.EGLContext;

public class CameraView extends FrameLayout {

    private CameraEglSurfaceView surfaceView;
    private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;

    public CameraView(@NonNull Context context) {
        this(context, null);
    }

    public CameraView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CameraView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        surfaceView = new CameraEglSurfaceView(getContext(), cameraId);
        addView(surfaceView);
    }

    @Override
    protected void onDetachedFromWindow() {
        release();
        super.onDetachedFromWindow();
    }

    public void release() {
        removeAllViews();
        if (surfaceView != null) {
            surfaceView.onDestroy();
            surfaceView = null;
        }
    }

    public void switchCamera() {
        if (isBackCamera()) {
            cameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
        } else {
            cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
        }
//        release();
//        init();
        surfaceView.switchCamera();
    }

    public boolean isBackCamera() {
        return cameraId == Camera.CameraInfo.CAMERA_FACING_BACK;
    }

    public EGLContext getEglContext() {
        if (surfaceView != null)
            return surfaceView.getEglContext();
        return null;
    }

    public int getCameraPrivewWidth() {
        if (surfaceView != null)
            return surfaceView.getCameraPrivewWidth();
        else return 0;
    }

    public int getCameraPrivewHeight() {
        if (surfaceView != null)
            return surfaceView.getCameraPrivewHeight();
        else return 0;
    }

    public int getTextureId() {
        if (surfaceView != null)
            return surfaceView.getTextureId();
        else return 0;
    }

    public int getCameraId() {
        if (surfaceView != null)
            return surfaceView.getCameraId();
        else
        return cameraId;
    }

    public void onDestroy() {
        if (surfaceView != null)
            surfaceView.onDestroy();
    }

    public void previewAngle(Context context) {
        if (surfaceView != null)
            surfaceView.previewAngle(context);
    }
}
